<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\Weixin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class WechatController extends Controller
{
    private $wechat;
    private $memberModel;
    private $weixinModel;

    public function __construct()
    {
        $this->wechat = app('wechat.official_account');
        $this->memberModel = new Member();
        $this->weixinModel = new Weixin();
    }



    /**授权
     * @return mixed
     */
    public function webOAuth()
    {
        return $this->wechat->oauth->scopes(['snsapi_userinfo'])->redirect();
    }


    /**
     * 获取用户信息
     */
    public function webcallback()
    {
        // 获取 OAuth 授权结果用户信息
        $user = $this->wechat->oauth->user();
        if($user['id']){
            $member = $this->memberModel->getMember(['openid'=>$user['id']],['id','openid','mobile']);
            if(empty($member)){
                $temp['openid'] = $user['original']['openid'];
                $temp['nickname'] = $user['original']['nickname'];
                $temp['avatar'] = $user['original']['headimgurl'];
                $temp['addtime'] = time();
                $get_weixin = $this->weixinModel->getWeixin(['openid'=>$temp['openid']]);
                if(!empty($get_weixin)){
                    $result['code'] = '1';
                    $result['data']['type'] = '2';
                    $result['data']['openid'] = $user['original']['openid'];
                }
                $bool = $this->weixinModel->addWeixin($temp);
                if($bool){
                    $result['code'] = '1';
                    $result['data']['type'] = '2';
                    $result['data']['openid'] = $user['original']['openid'];
                } else{
                    $result['code'] = '0';
                    $result['data']['type'] = '0';
                    $result['data']['openid'] = $user['original']['openid'];
                }
            }elseif (empty($member->mobile)){
                $result['code'] = '1';
                $result['data']['type'] = '2';
                $result['data']['openid'] = $user['original']['openid'];
            }else{
                $result['code'] = '1';
                $result['data']['type'] = '1';
                $result['data']['openid'] = $user['original']['openid'];
            }
        }else{
            $result['code'] = '0';
            $result['data']['type'] = '0';
            $result['data']['openid'] = '';
        }

        $url = URL::temporarySignedRoute('wechat.Todealwith',now()->addMinutes(60),[
            'code'=>$result['code'],
            'type'=>$result['data']['type'],
            'openid'=>$result['data']['openid']
        ]);
        $arr = explode('?',$url);
        $url = 'http://talentservice.rcfwlm.net/#/login_loading?'.$arr[1];
        return redirect($url);
    }


    /**
     * 请求数据处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function Todealwith(Request $request)
    {
        if (!$request->hasValidSignature()) {
            return response()->json(['code'=>'0','message'=>'非法请求']);
        }

        $data = $request->input();
        if($data['code'] == 0){
            $result = ['code'=>'1','message'=>'授权失败','data'=>['type'=>'0']];
        }elseif ($data['code'] == 1){
            if($data['type'] == 2){
                $result['code'] = '1';
                $result['message'] = '完善资料';
                $result['data']['type'] = '2';
                $result['data']['openid'] = $data['openid'];
            }else{
                $result = $this->getToken($data['openid']);
            }
        }

        return response()->json($result);
    }

    /**
     * 用户信息完善
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function perfectUser(Request $request)
    {
        $data = $request->input();
        $bool_data = $this->getValidator($data);
        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }elseif ($bool_data['code'] == 2){
            $result = $this->getToken($data['openid']);
            return response()->json($result);
        }

        $member_mobile = $this->memberModel->getMember(['mobile'=>$data['mobile']],['id','openid','mobile']);

        $temp['openid'] = $bool_data['data']->openid;
        $temp['nickname'] = $bool_data['data']->nickname;
        $temp['avatar'] = $bool_data['data']->avatar;
        if(!empty($member_mobile)){
            $bool = $this->memberModel
                ->updMember(['id'=>$member_mobile->id],$temp);
        }else{
            $temp['mobile'] = $data['mobile'];

            $insert_bool = $this->memberModel
                ->addMember($temp);
            if($insert_bool['code'] == 1){
                $bool = true;
            }else{
                $bool = false;
            }
        }

        if($bool){
            $result = $this->getToken($bool_data['data']['openid']);
        }else{
            $result = ['code'=>'0','message'=>'完善资料失败'];
        }
        return response()->json($result);
    }


    /**
     * token处理
     * @param $openid
     * @return \Illuminate\Http\JsonResponse
     */
    public function getToken($openid)
    {
        $member = $this->memberModel->getMember(['openid'=>$openid],['id','openid','mobile']);

        $customClaims = ['foo' => 'member'];
        $token = \Tymon\JWTAuth\Facades\JWTAuth::claims($customClaims)->fromUser($member);

        $login = new LoginController();
        return $login->respondWithToken($token,'member');
    }


    /**
     * 验证
     * @param $data
     * @return array
     */
    public function getValidator($data)
    {
        $validator = \Validator::make($data,[
            'openid'=>'required',
            'mobile'=>'required|integer',
            'code'=>'required|integer',
        ],[
            'required'=>':attribute为必填项',
            'max'=>':attribute长度不符合要求',
            'integer'=>':attribute必须为数字',
        ],[
            'openid'=>'微信openid',
            'mobile'=>'手机号码',
            'code'=>'验证码',
        ]);

        //验证失败，并返回第一个报错
        if($validator->fails()) {
            return ['code' => 0, 'message' => $validator->errors()->first()];
        }

        $weixin = $this->weixinModel->getWeixin(['openid'=>$data['openid']]);
        if(empty($weixin)){
            return ['code'=>'0','message'=>'微信授权失败，请重新授权'];
        }

        $member = $this->memberModel->getMember(['openid'=>$data['openid']],['id','openid','mobile']);
        if (!empty($member->mobile)){
            return ['code'=>'2','message'=>'您已经绑定过手机'];
        }



        $code = new NoteCodeController();
        $bool = $code->verifyCode($data);
        if($bool['code'] == 0){
            return $bool;
        }

        return ['code'=>1,'message'=>'验证成功','data'=>$weixin];
    }
}
